<template>
  <div id="app" class="cloth-order-change">
    <!-- 头部导航 -->
    <van-nav-bar
        ref="header"
        :title="title"
        left-arrow
        @click-left="comeBack"
        left-text="返回"
    >
      <template #right>
        <van-button v-if="ownerFlag" style="height:30px;" plain type="info" text="确认" @click="confirmChangeFn"></van-button>
      </template>
    </van-nav-bar>
    <van-form>
      <van-field label="单选框">
        <template #input>
          <van-radio-group :disabled="!ownerFlag" v-model="order.type" direction="horizontal">
            <van-radio name="1">试样</van-radio>
            <van-radio name="2">大货</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field label="客户">
        <template #input>
          <van-search v-if="ownerFlag" v-model="order.customerName" placeholder="请输入客户信息" @search="searchCustomerFn"></van-search>
          <span v-if="!ownerFlag">{{ order.customerName }}</span>
        </template>
      </van-field>
      <van-field readonly clickable v-model="order.deliveryAt" label="交货日期" placeholder="请选择" @click="showDatePickerPopup = ownerFlag">
      </van-field>
      <van-field :readonly="!ownerFlag" label="特别说明" type="textarea" autosize v-model="order.specialRemark" placeholder="请输入备注说明">
      </van-field>
    </van-form>

    <!-- 子订单 -->
    <van-collapse accordion v-model="activeCollapseItem" @change="showSubOrderFn">
      <van-collapse-item v-for="(detail, index) in details" :key="'detail_' + index " :name="index" style="border-top:1px solid #a12828">
        <template #title>
          <div style="display: flex; justify-content: space-between">
            <div>
              <span>{{ detail.designNo + '(' + detail.color + ')' }}</span>
            </div>
            <div style="display: flex;">
              <van-tag v-for="(tag,tagIndex) in detail.tags" mark :key="tagIndex" :color="tag.color" >{{ tag.name }}</van-tag>
            </div>
          </div>
        </template>
        <template>
          <van-swipe-cell>
            <van-card :title="detail.designNo + '(' + detail.color + ')'" :desc="detail.customNo + '(' + detail.customColor + ')'" :price="detail.metre" :num="detail.num">
              <template #thumb>
                <van-image width="80px" height="80px" :src="detail.firstPic" @click="showImagePreViewFn(detail)">
                  <template v-slot:error>加载失败</template>
                </van-image>
              </template>
              <template #price>
                <span style="font-size: 20px;color: #1989fa;font-weight: bold">米数: {{ detail.metre }}</span>
              </template>
              <template #num>
                <span style="font-size: 16px;color: #0c8aaf;font-weight: bold">匹数: {{ detail.num }}</span>
              </template>
              <template #footer>
                <div style="margin-top:15px;">
                  <van-button plain  text="纱线库存" type="warning" @click="showStockPopupFn(1, detail, index)"></van-button>
                  <van-button plain  text="坯布库存" type="info" @click="showStockPopupFn(2, detail, index)"></van-button>
                  <van-button plain  text="成品库存" type="danger" @click="showStockPopupFn(3, detail, index)"></van-button>
                </div>
              </template>
            </van-card>
            <template #right>
              <van-button v-if="ownerFlag" square text="删除" type="danger" @click="cancelSubOrderFn(index)" />
              <van-button v-if="ownerFlag" style="margin-top:5px;" square text="修改" type="primary" @click="changeDetailFn(detail, index)" />
              <van-button style="margin-top:5px;" square text="环节" type="info" @click="viewStepFn(detail)" />
            </template>
          </van-swipe-cell>
        </template>
      </van-collapse-item>
    </van-collapse>

    <div v-if="ownerFlag" style="display: flex; justify-content: center; align-items: center;margin-top:15px">
      <van-button type="primary" text="增加详情" style="width: 70%;font-size: 22px;" @click="addNewDetailFn"></van-button>
    </div>

    <!-- 图片预览 -->
    <van-image-preview v-model="showImagePreView" :images="preViewPics.map(viewPic => viewPic.url)"></van-image-preview>

    <!-- 日期弹窗 -->
<!--    <van-popup v-model="showDatePickerPopup" position="bottom">
      <van-datetime-picker type="date" title="选择交货日期" :min-date="minDate" :max-date="maxDate" @confirm="confirmDateFn" @cancel="cancelDateFn">
      </van-datetime-picker>
    </van-popup>-->
    <van-calendar v-model="showDatePickerPopup"  title="交货日期" :show-confirm="false" @confirm="confirmDateFn" />

    <!-- 修改弹窗 -->
    <van-popup v-model="showChangeDetailPopup" class="change-detail-popup">
      <van-form label-align="right" input-align="left">
        <van-field label="客户品号" v-model="curDetail.customNo" placeholder="请输入客户品号" @blur="viewUpdateFn"></van-field>
        <van-field label="客户颜色" v-model="curDetail.customColor" placeholder="请输入客户颜色" @blur="viewUpdateFn"></van-field>
        <div style="padding: 1vh 2vw;">
          <div style="display: flex;justify-content: center"><span style="font-size: 0.8rem;">来样图片</span></div>
          <div style="display: flex;flex-wrap: wrap;align-items: center">
            <div style="position:relative;" v-if="curDetail.customThumbPics.length > 0"  v-for="(picObj, pIndex) in curDetail.customThumbPics">
              <van-image width="20vw" height="20vw" :src="picObj.url" @click="showImagePreViewSingleFn(picObj)"></van-image>
              <van-icon style="position:absolute;top:0;right:0" name="clear" @click="delPicFn(curDetail.customThumbPics, picObj, pIndex)"></van-icon>
            </div>
            <van-uploader v-model="curDetail.customPicFiles" multiple :max-count="10" :after-read="(file, detail) => afterReadFileFn(file, detail, 'customPic')" @delete="(file, detail) => deleteFileFn(file, detail, 'customPic')"></van-uploader>
          </div>
        </div>
        <div style="padding: 1vh 2vw;">
          <div style="display: flex;justify-content: center"><span style="font-size: 0.8rem;">资料图片</span></div>
          <div style="display: flex;flex-wrap: wrap;align-items: center">
            <div style="position: relative" v-if="curDetail.docThumbPics.length > 0"  v-for="(picObj, pIndex) in curDetail.docThumbPics">
              <van-image width="20vw" height="20vw" :src="picObj.url" @click="showImagePreViewSingleFn(picObj)"></van-image>
              <van-icon style="position:absolute;top:0;right:0" name="clear" @click="delPicFn(curDetail.docThumbPics, picObj, pIndex)"></van-icon>
            </div>
            <van-uploader v-model="curDetail.docPicFiles" multiple :max-count="10" :after-read="(file, detail) => afterReadFileFn(file, detail, 'docPic')" @delete="(file, detail) => deleteFileFn(file, detail, 'docPic')"></van-uploader>
          </div>
        </div>
        <van-field label="本厂品号">
          <template #input>
            <van-search v-model="curDetail.designNo" placeholder="请筛选品号" @search="searchDesignFn"></van-search>
          </template>
        </van-field>
        <van-field label="产品图">
          <template #input>
            <van-image width="100px" height="100px" :src="curDetail.samplePicUrl" @click="showImagePreViewFn([curDetail.samplePicUrl])">
              <template v-slot:error>加载失败</template>
            </van-image>
            <van-image width="100px" height="100px" :src="curDetail.productPicUrl" @click="showImagePreViewFn([curDetail.productPicUrl])">
              <template v-slot:error>加载失败</template>
            </van-image>
          </template>
        </van-field>
        <van-field label="颜色">
          <template #input>
            <van-search v-model="curDetail.color" placeholder="请输入色号" @search="searchColorFn"></van-search>
            <van-button type="info" plain text="增加" style="height: 34px;width: 80px;padding:0px;" @click="showAddColorPopup = true"></van-button>
          </template>
        </van-field>
        <van-field label="米数" v-model="curDetail.metre" clearable placeholder="请输入米数" type="digit" @input.native="calFieldFn('metre')" @focus="toClearFieldFn('metre')" ></van-field>
        <van-field label="匹数" v-model="curDetail.num" clearable placeholder="请输入匹数" type="digit" @input.native="calFieldFn('num')" @focus="toClearFieldFn('num')" ></van-field>
        <van-field label="匹长" v-model="curDetail.length" clearable placeholder="请输入匹长" type="digit" @input.native="calFieldFn('length')" @focus="toClearFieldFn('length')" ></van-field>

        <div style="display: flex;justify-content: center;align-items: center; margin-top:20px; padding-right:20px;">
          <van-button text="取消" type="danger" @click="showChangeDetailPopup = false"></van-button>
          <van-button text="确认修改" type="primary" @click="confirmSubOrderFn"></van-button>
        </div>
      </van-form>
    </van-popup>

    <!-- 客户弹窗 -->
    <van-popup v-model="showCustomerPopup" position="bottom" get-container="#app">
      <van-picker show-toolbar value-key="name" :columns="customerData" @confirm="confirmCustomerFn" @cancel="showCustomerPopup = false" />
    </van-popup>

    <!-- 品名弹窗 -->
    <van-popup v-model="showDesignPopup" position="bottom" get-container="#app">
      <van-picker show-toolbar value-key="name" :columns="designNoData" @confirm="confirmDesignNoFn" @cancel="showDesignPopup = false" />
    </van-popup>

    <!-- 颜色弹窗 -->
    <van-popup v-model="showColorPopup" position="bottom" get-container="#app">
      <van-picker show-toolbar value-key="vName" :columns="colorNoData" @confirm="confirmColorNoFn" @cancel="showColorPopup = false" />
    </van-popup>

    <!-- 增加弹窗 -->
    <van-popup round v-model="showAddColorPopup" style="width: 80%" get-container="#app" closeable @closed="showAddColorPopup = false">
      <van-form>
        <van-field style="margin-top: 20px;" colon label="色号" label-width="60" label-align="right" placeholder="请输入色号" v-model="colorParam.no"></van-field>
        <van-field colon label="名称" label-width="60" label-align="right" placeholder="请输入名称" v-model="colorParam.name"></van-field>
        <van-field colon label="英文名" label-width="60" label-align="right" placeholder="请输入英文名称" v-model="colorParam.enName"></van-field>
        <div style="display: flex;justify-content: center; align-items: center; margin: 10px 0px;">
          <van-button type="primary" text="增加" @click="addDyeColorFn"></van-button>
        </div>
      </van-form>
    </van-popup>


    <!-- 纱线库存 -->
    <van-popup round v-model="showYarnStockPopup" style="width: 80%; height: 80%" get-container="#app" closeable @closed="showYarnStockPopup = false">
      <div style="text-align: center;font-size: 26px;font-weight: bold;margin-top:10px;color: #545dc5">
        <span>纱线库存</span>
      </div>
      <div style="margin-top: 15px;height: 87%;overflow: auto;display: flex;flex-direction: column;align-items: center;">
        <div v-for="(detail4Stock, index) in detail4Stocks" :key="index" style="width: 90%;box-shadow: 5px 5px 5px #888888;margin-top: 10px;">
          <van-row style="padding: 5px;">
            <van-col>
              <span style="color: #0c8aaf">编号: {{ detail4Stock.standardNo }}</span>
            </van-col>
          </van-row>
          <van-row style="padding: 5px;">
            <van-col>
              <span style="color: #96b327">名称: {{ detail4Stock.yarnNo }}</span>
            </van-col>
          </van-row>
          <van-row style="padding: 5px;">
            <van-col>
              <span style="color: #6e3ac5">规格: {{ detail4Stock.yarnStandard + "/" + detail4Stock.yarnStrandNum }}</span>
            </van-col>
            <van-col :offset="2">
              <span style="color: #522791">需求: {{ detail4Stock.expectUsage }}</span>
            </van-col>
          </van-row>
          <van-row style="padding: 5px;" :style="detail4Stock.stockStyle">
            <van-col>
              <span>实际: {{ detail4Stock.stock }}</span>
            </van-col>
            <van-col :offset="1">
              <span>预计: {{ detail4Stock.expectStock }}</span>
            </van-col>
          </van-row>
        </div>
      </div>
    </van-popup>

    <!-- 坯布/成品库存弹窗 -->
    <van-popup round v-model="showClothStockPopup" style="width: 80%; height: 80%" get-container="#app" closeable @closed="showClothStockPopup = false">
      <div style="text-align: center;font-size: 20px;font-weight: bold;margin-top:10px;color: #545dc5">
        <span>{{ viewStockFlag == 2 ? "坯布" : viewStockFlag == 3 ? "成品库存" : SPLIT_BLANK }}</span>
      </div>
      <div style="margin-top: 15px;height: 87%;overflow: auto;display: flex;flex-direction: column;align-items: center;">
        <div v-for="(detail4Stock, index) in detail4Stocks" :key="index" style="width: 90%;box-shadow: 5px 5px 5px #888888;margin-top: 10px;" @click="selectDesignNoFn(detail4Stock)">
          <van-row style="padding: 5px;">
            <van-col>
              <span style="color: #0c8aaf">品号: {{ detail4Stock.designNo }}</span>
            </van-col>
          </van-row>
          <van-row style="padding: 5px;">
            <van-col>
              <span style="color: #96b327">颜色: {{ detail4Stock.color }}</span>
            </van-col>
          </van-row>
          <van-row style="padding: 5px;" :style="detail4Stock.stockStyle">
            <van-col>
              <span>匹数: {{ detail4Stock.totalNum }}</span>
            </van-col>
            <van-col :offset="1">
              <span>米数: {{ detail4Stock.length }}</span>
            </van-col>
            <van-col :offset="1">
              <span>预计: {{ detail4Stock.expectNum }}</span>
            </van-col>
          </van-row>
        </div>
      </div>
    </van-popup>

    <!-- 部门岗位弹窗 -->
<!--    <van-popup round v-model="showPostPopup" style="width: 85%; height: 80%" get-container="#app" closeable @closed="showPostPopup = false">
      <div style="text-align: center;font-size: 20px;font-weight: bold;padding:10px 0px;color: #545dc5">
        <span>选择部门</span>
      </div>
      <div style="height: 65%;overflow: auto">
        <van-checkbox-group v-model="postCheckedData">
          <van-checkbox v-for="post in postData" :key="post.id" :name="post" :disabled="post.disabled" shape="square">{{ post.name }}({{ post.firstUser }})</van-checkbox>
        </van-checkbox-group>
      </div>
      <div style="border: 1px solid #afb601;">
        <van-field type="textarea" label-class="van-field-label-remark" label-width="80px" label="派单留言:" rows="2" show-word-limit maxlength="1024" label-align="right" placeholder="请输入备注内容,可不填" v-model="specialRemark"></van-field>
      </div>
      <div style="display: flex; justify-content: center; margin-top:10px;">
        <van-button style="width: 180px; margin-left: 15px;" type="primary" @click="appointTaskFn">任务派单</van-button>
      </div>
    </van-popup>-->

    <!-- 任务列表弹窗 -->
<!--    <van-popup round v-model="showOrderTaskPopup" style="width: 80%; height: 80%" get-container="#app" closeable @closed="showPostPopup = false">
      <div style="text-align: center;font-size: 26px;font-weight: bold;padding:10px 0px;color: #545dc5">
        <span>任务列表</span>
      </div>
      <div style="height: 80%;overflow: auto">
        <div v-for="task in orderTaskData" :key="task.id" class="order-task-card" :style="taskBackgroundColorFn(task)">
          <van-row style="color: #6e3ac5; font-size: 18px; font-weight: bold; margin-top:20px;border-bottom: 1px solid #6e3ac5">
            <van-col :span="4" style="text-align: right">
              部门:
            </van-col>
            <van-col :span="8">
              <span>{{ task.depPostName }}</span>
            </van-col>
            <van-col :span="4" style="text-align: right">
              状态:
            </van-col>
            <van-col :span="6">
              <span>{{ task.statusName }}</span>
            </van-col>
            <van-col v-if="task.mine">
              <van-tag color="#007a24">我</van-tag>
            </van-col>
          </van-row>
          <van-row class="van-row-appoint">
            <van-col :span="6" class="task-label">
              派单人:
            </van-col>
            <van-col class="task-body">
              <span>{{ task.appointorName }}</span>
            </van-col>
          </van-row>
          <van-row class="van-row-appoint">
            <van-col :span="6" class="task-label">
              派单时间:
            </van-col>
            <van-col class="task-body">
              <span>{{ task.appointAt }}</span>
            </van-col>
          </van-row>
          <van-row class="van-row-appoint" style="border-bottom: 1px solid #2083fd">
            <van-col :span="6" class="task-label">
              <span>派单备注:</span>
            </van-col>
            <van-col class="task-body">
              <span>{{ task.appointRemark }}</span>
            </van-col>
          </van-row>
          <van-row class="van-row-accept">
            <van-col :span="6" class="task-label">
              接单人:
            </van-col>
            <van-col class="task-body">
              <span>{{ task.executiveName }}</span>
            </van-col>
          </van-row>
          <van-row class="van-row-accept">
            <van-col :span="6" class="task-label">
              <span>接单时间:</span>
            </van-col>
            <van-col class="task-body">
              <span>{{ task.acceptAt }}</span>
            </van-col>
          </van-row>
          <div v-show="(task.status == 3 || task.status == 4) || !task.mine">
            <van-row class="van-row-accept">
              <van-col :span="6" class="task-label">
                <span>操作备注:</span>
              </van-col>
              <van-col class="task-body">
                <span>{{ task.executiveRemark }}</span>
              </van-col>
            </van-row>
            <van-row class="van-row-accept">
              <van-col :span="6" class="task-label">
                <span>完成时间:</span>
              </van-col>
              <van-col class="task-body">
                <span>{{ task.remarkAt }}</span>
              </van-col>
            </van-row>
          </div>
          &lt;!&ndash; 处理 &ndash;&gt;
          <div v-show="(task.status != 3 && task.status != 4) && task.mine">
            <van-row class="van-row-accept">
              <van-col :span="6" class="task-label">
                <span>操作备注:</span>
              </van-col>
              <van-col style="margin-left:5px;">
                <van-field style="padding: 0px 5px; background: #ece17d" v-model="executiveRemark" placeholder="请输入备注内容" type="textarea"></van-field>
              </van-col>
            </van-row>
            <div style="display: flex; justify-content: center; margin-top: 10px;">
              <van-button v-if="task.appointorId != 0" style="width: 100px;height: 30px;margin: 10px 5px;" type="danger" @click="rejectTaskFn(task)">驳回</van-button>
              <van-button style="width: 100px;height: 30px;margin: 10px 5px;" type="primary" @click="() => showPostPopupFn(task)">派单</van-button>
              <van-button style="width: 100px;height: 30px;margin: 10px 5px;" type="warning" @click="finishTaskFn(task)">完成</van-button>
            </div>
          </div>
          &lt;!&ndash; 撤销 &ndash;&gt;
          <div v-show="task.status != 3 && task.status != 4 && task.appointorId == getInfo().userId" style="display: flex; justify-content: center; margin-top: 10px">
            <van-button style="width: 200px;height: 30px;margin: 10px 5px;" type="warning" @click="cancelTaskFn(task)">撤销任务</van-button>
          </div>
        </div>
      </div>
      <div style="display: flex; justify-content: center; margin-top:10px;">
        <van-button style="width: 220px;" type="info" @click="showOrderTaskPopup = false">关闭</van-button>
      </div>
    </van-popup>-->

    <!-- 环节处理 -->
    <van-popup style="max-height: 70vh;overflow: auto;" v-model="step.show" get-container="#app">
      <div style="padding:1vh 4vw 1vh 2vw;width: 90vw;">
        <div style="margin-bottom: 2vh;border: 1px #2083fd solid;padding:1vh 1vw;box-shadow: 5px 5px 10px rgba(32, 131, 253, 0.5)" v-for="s in step.data">
          <div :style="{ display: 'flex', justifyContent: 'space-between', alignItems: 'center',marginBottom: '2vh', color: (s.status == 1 ? '#c94949' : s.status == 2 ? '#e78828' : s.status == 3 ? '#41d249' : '#4d4d4d') }">
            <div><span style="font-weight: bolder">{{ s.stepName }}</span></div>
            <div><span>{{ s.optName }}</span></div>
            <div><span>{{ orderTaskStatusEnum(s.status) }}</span></div>
          </div>
          <div  v-if="s.status != 3 && s.status != 1" style="display: flex; justify-content: right; color: #E78828;">
            <div><span>最近操作时间:</span><span>{{ s.lastOptAt }}</span></div>
          </div>
          <div v-if="s.status == 3" style="display: flex; justify-content: right;color: #41D249">
            <div><span>完成时间:</span><span>{{ s.finishAt }}</span></div>
          </div>
          <div style="display: flex;justify-content: space-between; align-items: center; font-size: 0.8rem" v-for="optR in s.opts">
            <div style="flex: 1">
              <span v-if="!optR.c">{{ optR.text }}</span>
              <van-field v-if="optR.c && (s.status == 1 || s.status == 2) && s.optFlag" :colon="true" :autosize="{minHeight: 60}" label-align="right" label-width="16vw" type="textarea" label="操作备注"  placeholder="请输入处理备注" v-model="optR.text"></van-field>
            </div>
            <div v-if="!optR.c" style="flex: 0 0 34vw;">
              <span>{{ optR.t }}</span>
            </div>
          </div>
          <div>
            <div v-if="s.optFlag" style="display: flex;justify-content: space-between">
              <van-button v-if="s.status == 1" type="danger" size="small" @click="handleStepFn(s, 4)">不用处理</van-button>
              <van-button v-if="s.status == 1" type="warning" size="small" @click="handleStepFn(s, 2)">接单</van-button>
              <van-button v-if="s.status == 2" type="warning" size="small" @click="handleStepFn(s, 2)">处理</van-button>
              <van-button v-if="s.status == 2" type="primary" size="small" @click="handleStepFn(s, 3)">完成</van-button>
            </div>
          </div>
        </div>
<!--        <div style="display: flex;justify-content: center;align-items: center">
          <van-button type="danger" size="small" @click="step.show = false">关闭</van-button>
          <van-button type="warning" size="small" @click="">处理</van-button>
        </div>-->
      </div>
    </van-popup>
  </div>
</template>

<script>
import {deepCopy, comeBack, getFloat} from "@/utils";
import dayjs from "dayjs";
import {getUploadKey} from "@/api/public";
import {exportBaseUrl} from "@/utils/request";
import {filterDesignByNo, getCustomerInfoList} from "@/api/product";
import {
  acceptTask,
  addDyeColor,
  addOrder,
  addSubOrder,
  appointTask, cancelTask,
  changeOrder,
  changeSubOrder,
  cancelSubOrder,
  dyeColorFilter, finishTask,
  loadClothSubOrder,
  loadGreyClothStore, loadOrderTaskBySubOrder,
  loadPost,
  loadProductClothStore,
  loadSampleYarn, loadYarnStandardBatch, orderTaskStatusEnum,
  orderUserStatusEnum, rejectTask, changeSubOrderDesign, handleStep
} from "@/api/order";
import {getInfo} from "@/utils/auth";
import {SPLIT_BLANK, SPLIT_COMMA, SPLIT_ZKH} from "@/api/enum";
import {
  genImgUrl,
  loadLocal4DataUrlFn,
  loadLocalPicFn,
  loadPic,
  loadPicThumb,
  localPicFn,
  uploadPic
} from "@/components/file-upload/upload_file";

export default {
  name: "clothOrderChange",
  data() {
    return {
      SPLIT_BLANK,

      title: "布匹订单-增改",
      minDate: new Date(2022, 0, 1),
      maxDate: new Date(2050, 11, 1),
      showDatePickerPopup: false,   //展示时间筛选

      //主订单
      order: {
        type: "2",
        channel: 0,
        customerId: 0,
        customerName: SPLIT_BLANK,
        deliveryAt: dayjs().format("YYYY-MM-DD"),
        specialRemark: SPLIT_BLANK,
        totalMetre: 0,
        totalNum: 0,
      },

      //子订单
      showChangeDetailPopup: false,   //展示更改详情弹出框
      activeCollapseItem: "0",
      curDetail: {
        flag: 1,    //0-原来; 1-新增; 2-修改; 3-删除
        customNo: SPLIT_BLANK,
        customColor: SPLIT_BLANK,
        customPic: SPLIT_BLANK,
        docPic: SPLIT_BLANK,
        designId: SPLIT_BLANK,
        designNo: SPLIT_BLANK,
        color: SPLIT_BLANK,
        num: SPLIT_BLANK,
        metre: SPLIT_BLANK,
        length: SPLIT_BLANK,
        // pics: [],
        samplePicUrl: SPLIT_BLANK,
        productPicUrl: SPLIT_BLANK,
        customPicUrl: SPLIT_BLANK,



        customPicFiles: [],
        docPicFiles: [],
        firstPic: SPLIT_BLANK,
        viewPics: [],

        customThumbPics: [],   //客户来样缩略图
        docThumbPics: [],    //资料文件缩略图

      },    //最近一个详情,新增复制用,
      calTimer: null,
      curDetailIndex: 0,
      curTask: null,
      details: [/*{
        flag: 1,    //0-原来; 1-新增; 2-修改; 3-删除
        customNo: SPLIT_BLANK,
        customColor: SPLIT_BLANK,
        customPic: SPLIT_BLANK,
        designId: SPLIT_BLANK,
        designNo: SPLIT_BLANK,
        color: SPLIT_BLANK,
        num: SPLIT_BLANK,
        metre: SPLIT_BLANK,
        pics: [require("@/views/order/cloth-order/YPSJD_220727143628GgD6e_1.jpg")]
      }*/],

      preViewPics: [],
      showImagePreView: false,

      //客户筛选
      showCustomerPopup: false,
      customerData: [],

      //品名筛选
      showDesignPopup: false,
      designNoData: [],

      //颜色筛选
      showColorPopup: false,
      colorNoData: [],

      //增加颜色
      showAddColorPopup: false,
      colorParam: {
        no: SPLIT_BLANK,
        name: SPLIT_BLANK,
        enName: SPLIT_BLANK
      },

      //查看库存
      viewStockFlag: 0,
      detail4Stocks: [],
      showYarnStockPopup: false,
      showClothStockPopup: false,
      stockStyle: [],

      //部门岗位选择
      showPostPopup: false,
      postData: [],
      postCheckedData: [],
      specialRemark: SPLIT_BLANK,

      //订单任务
      showOrderTaskPopup: false,
      orderTaskData: [],
      executiveRemark: SPLIT_BLANK,
      selectStock: null,

      /* 所有人标记 */
      ownerFlag: false,
      /* 环节 */
      step: {
        show: false,
        data: [],
      }
    }
  },
  mounted() {
    const that = this;
    if (process.env.NODE_ENV === "production") {
      this.$nextTick(() => {
        that.initFn();
      });
    } else {
      window.apiready = function () {
        that.initFn();
      }
    }
  },
  methods: {
    comeBack,
    getInfo,
    orderTaskStatusEnum,
    //初始化
    initFn() {
      const that = this;
      window.api.addEventListener({
        name: "viewdisappear"
      }, function() {
        window.api.closeWin();
      });

      let order = window.api.pageParam.order;
      that.ownerFlag = order.ownerFlag;   //下单人标记

      if(order.id > 0) {
        //回显
        Object.keys(order).forEach(key => {
          if("type" == key) {
            order[key] = order[key].toString();
          }
          that.order[key] = order[key];
        });

        that.loadClothSubOrderFn(that, order.id);
      }
    },

    /* 加载订单详情 */
    loadClothSubOrderFn(that, orderId) {
      //请求详情
      that.details.splice(0, that.details.length);
      loadClothSubOrder({
        orderId: orderId
      }, data => {
        if(data.code || data.code == 0) {
          that.$toast.fail(data.msg);
          return;
        }
        data.filter(subOrder => subOrder.status != 4).forEach(subOrder => {
          subOrder.flag = 0;    //原有
          subOrder.customPicUrl = SPLIT_BLANK;   //这里先赋值了,才是动态绑定
          subOrder.samplePicUrl = SPLIT_BLANK;
          subOrder.productPicUrl = SPLIT_BLANK;
          subOrder.docPicUrl = SPLIT_BLANK;

          //以下图片异步加载问题不大,因为需要点开查看
          /*subOrder.pics = [];   //全部预览图 todo 挪地方
          if(subOrder.docPic && subOrder.docPic != SPLIT_BLANK) {
            subOrder.docPicUrls = [];
            subOrder.docPic.split(SPLIT_COMMA).forEach(pic => {
              getUploadKey({
                type: "YPSJD"
              }, tokenRes => {
                let docPicUrl  = exportBaseUrl("res") + "/res/" + pic + '?accessToken=' + tokenRes.accessToken;
                subOrder.pics.push(docPicUrl);
                subOrder.docPicUrl = docPicUrl;
                subOrder.docPicUrls.push(docPicUrl);
              });
            });
          }
          if(subOrder.customPic && subOrder.customPic != SPLIT_BLANK) {
            getUploadKey({
              type: "YPSJD"
            }, tokenRes => {
              let customPicUrl  = exportBaseUrl("res") + "/res/" + subOrder.customPic + '?accessToken=' + tokenRes.accessToken;
              subOrder.pics.push(customPicUrl);
              subOrder.customPicUrl = customPicUrl;
            });
          }
          if(subOrder.samplePic && subOrder.samplePic != SPLIT_BLANK) {
            getUploadKey({
              type: "YPSJD"
            }, tokenRes => {
              let samplePicUrl  = exportBaseUrl("res") + "/res/" + subOrder.samplePic + '?accessToken=' + tokenRes.accessToken;
              subOrder.pics.push(samplePicUrl);
              subOrder.samplePicUrl = samplePicUrl;
            });
          }
          if(subOrder.productPic && subOrder.productPic != SPLIT_BLANK) {
            getUploadKey({
              type: "YPSJD"
            }, tokenRes => {
              let productPicUrl  = exportBaseUrl("res") + "/res/" + subOrder.productPic + '?accessToken=' + tokenRes.accessToken;
              subOrder.pics.push(productPicUrl);
              subOrder.productPicUrl = productPicUrl;
            });
          }*/

          subOrder.firstPic = SPLIT_BLANK;    //首图
          that.loadFirstPicFn(subOrder);
          subOrder.viewPics = [];   //预览图
          subOrder.customPicFiles = [];   //客户来样图上传
          subOrder.docPicFiles = [];    //资料文件图上传

          subOrder.customThumbPics = [];   //客户来样缩略图
          subOrder.docThumbPics = [];    //资料文件缩略图
          subOrder.length = getFloat(subOrder.metre / subOrder.num, 0);
          that.details.push(subOrder);

          //加任务标记
          /*subOrder.tags = [];   //子任务标签
          subOrder.tasks.forEach(task => {
            if(!task.userStatus) return;
            let tag = orderUserStatusEnum(task.userStatus);
            if(!subOrder.tags.some(t => t.name == tag)) {
              subOrder.tags.push({
                "value": task.userStatus,
                "name": tag,
                "color": task.userStatus == 1 ? "#a9156f" : task.userStatus == 2 ? "#a9740f" : task.userStatus == 3 ? "#06347a" : task.userStatus == 4 ? "#69048a" : task.userStatus == 5 ? "#830407" : task.userStatus == 6 ? "#fda7af" : SPLIT_BLANK
              });
            }
          });*/
        });
      });
    },

    //日期选择
    confirmDateFn(value) {
      let that = this;
      that.order.deliveryAt = dayjs(value).format("YYYY-MM-DD");
      that.showDatePickerPopup = false;
    },
    /*cancelDateFn() {
      let that = this;
      that.showDatePickerPopup = false;
    },*/

    //删除详情
    cancelSubOrderFn(index) {
      let that = this;
      if(that.details.length == 1) {
        that.$toast.fail("至少需要一个详情");
        return;
      }
      let detailCur = that.details[index];
      if(detailCur.flag == 0) {
        let cancelRemark = prompt("请必须输入取消原因,还少4个字");
        if(cancelRemark && cancelRemark.length > 3) {
          //远程删除
          cancelSubOrder({
            subOrderId: detailCur.id,
            cancelRemark: cancelRemark
          }, () => {
            that.$toast.success("删除成功");
            that.details.splice(index, 1);
          });
        } else {
          that.$toast.fail("子订单未取消")
        }
      } else {
        that.details.splice(index, 1);
      }
    },
    //增加新详情
    addNewDetailFn() {
      let that = this;
      let lastItem = null;
      // if(that.details.length > 0) {
      //   lastItem = that.details[that.details.length - 1];
      //   that.curDetail = deepCopy(lastItem);
      // }
      that.curDetail.id = 0;
      that.curDetail.designId = SPLIT_BLANK;
      that.curDetail.designNo = SPLIT_BLANK;
      that.curDetail.color = SPLIT_BLANK;
      that.curDetail.customPic = SPLIT_BLANK;
      that.curDetail.customPicUrl = SPLIT_BLANK;
      that.curDetail.samplePicUrl = SPLIT_BLANK;
      that.curDetail.productPicUrl = SPLIT_BLANK;
      that.curDetail.metre = SPLIT_BLANK;
      that.curDetail.num = SPLIT_BLANK;
      that.curDetail.length = 68;
      // that.curDetail.pics.splice(0, that.curDetail.pics.length);
      that.curDetail.flag = 1;

      that.curDetail.customPic = SPLIT_BLANK;
      that.curDetail.docPic = SPLIT_BLANK;
      that.curDetail.customPicFiles.splice(0, that.curDetail.customPicFiles.length);
      that.curDetail.docPicFiles.splice(0, that.curDetail.docPicFiles.length);
      that.curDetail.firstPic = SPLIT_BLANK;
      that.curDetail.viewPics.splice(0, that.curDetail.viewPics.length);
      that.curDetail.customThumbPics.splice(0, that.curDetail.customThumbPics.length);
      that.curDetail.docThumbPics.splice(0, that.curDetail.docThumbPics.length);

      that.showChangeDetailPopup = true;
    },

    //修改详情
    changeDetailFn(subOrder, index) {
      const that = this;

      // if(detail.picKV) {
        /*if(detail.docPic && detail.docPic != SPLIT_COMMA) {
          detail.docPic.split(SPLIT_COMMA).forEach(pic => {

            loadPic(that, pic, data => {
              loadLocalPicFn(that, data, base64Data => {
                detail.docPicFiles.push({
                  content: base64Data
                });
                console.log(detail.docPicFiles)
                that.$forceUpdate();
              })


            })

          });
        }
        if(detail.customPic && detail.customPic != SPLIT_COMMA) {
          detail.customPic.split(SPLIT_COMMA).forEach(pic => {

            // detail.customPicFiles.push(detail.picKV[pic]);

            loadPic(that, pic, data => {
              detail.customPicFiles.push({
                url: genImgUrl(data),
                fileName: pic
              });
            })
          });
        }*/
      // } else {
      //
      // }


      /*that.curDetail.docPicFiles.splice(that.curDetail.docPicFiles, that.curDetail.docPicFiles.length);
      if(detail.docPic && detail.docPic != SPLIT_COMMA) {
        detail.docPic.split(SPLIT_COMMA).forEach(pic => {

          loadPic(that, pic, data => {
            /!*that.curDetail.docPicFiles.push({
              url: genImgUrl(data)
            });*!/
            loadLocalPicFn(that, data, base64Data => {
              that.curDetail.docPicFiles.push({
                // url: genImgUrl(data),
                content: base64Data
              });
            })


          })

        });
      }*/

      Object.keys(subOrder).forEach(k => {
        let v = subOrder[k];
        if(Array.isArray(v)) {
          if(!that.curDetail[k]) {
            that.curDetail[k] = [];
          } else {
            that.curDetail[k].splice(0, that.curDetail[k].length);
          }
          v.forEach(item => {
            that.curDetail[k].push(item);
          })
        } else {
          that.curDetail[k] = v;
        }
      });
      that.curDetail.customPicFiles.splice(0, that.curDetail.customPicFiles);
      that.curDetail.docPicFiles.splice(0, that.curDetail.docPicFiles);


      // that.curDetail = deepCopy(detail);
      that.curDetail.flag = 2;
      that.curDetailIndex = index;    //当前数据下标

      /*if(that.curDetail.viewPics.length > 0) {
        that.curDetail.viewPics.forEach(picUrl => {
          console.log(picUrl);
          loadLocal4DataUrlFn(picUrl).then(data => that.curDetail.customPicFiles.push(data));
        });
      }*/

      //不用管异步,会自动显示
      if(subOrder.customThumbPics.length == 0 && subOrder.customPic && subOrder.customPic != SPLIT_COMMA) {
        subOrder.customPic.split(SPLIT_COMMA).forEach(pic => {
          loadPicThumb(that, pic, dataUrl => {
            subOrder.customThumbPics.push({
              name: pic,
              url: dataUrl
            });
            that.curDetail.customThumbPics.push({
              name: pic,
              url: dataUrl
            });
          });
        });
      }
      if(subOrder.docThumbPics.length == 0 && subOrder.docPic && subOrder.docPic != SPLIT_COMMA) {
        subOrder.docPic.split(SPLIT_COMMA).forEach(pic => {
          loadPicThumb(that, pic, dataUrl => {
            subOrder.docThumbPics.push({
              name: pic,
              url: dataUrl
            });
            that.curDetail.docThumbPics.push({
              name: pic,
              url: dataUrl
            });
          });
        });
      }

      that.showChangeDetailPopup = true;
    },

    /* 文件读取后 */
    afterReadFileFn(file, detail, field) {
      /*const that = this;
      let tmpArr = that.curDetail[field].split(SPLIT_COMMA);
      tmpArr.push("toAddFileName");
      that.curDetail[field] = tmpArr.join(SPLIT_COMMA);*/
    },
    /* 文件删除后 */
    deleteFileFn(file, detail, field) {
      /*const that = this;
      let tmpArr = that.curDetail[field].split(SPLIT_COMMA);
      tmpArr.pop();
      that.curDetail[field] = tmpArr.join(SPLIT_COMMA);*/
    },


    //确认修改子订单
    confirmSubOrderFn() {
      let that = this;
      if(that.curDetail.designNo == SPLIT_BLANK) {
        that.$toast.fail("必须输入品名");
        return;
      }

      that.$toast.loading({
        message: '执行中...',
        forbidClick: true,
        loadingType: 'spinner',
      });

      if(that.curDetail.customPicFiles.length > 0) {
        that.uploadPicFn(that.curDetail.customPicFiles, resData => {
          that.curDetail.customPic += (SPLIT_COMMA + resData);
          that.curDetail.customPicFiles.splice(0, that.curDetail.customPicFiles.length);
          that.confirmSubOrderFn();
        });
        return;
      }
      if(that.curDetail.docPicFiles.length > 0) {
        that.uploadPicFn(that.curDetail.docPicFiles, resData => {
          that.curDetail.docPic += (SPLIT_COMMA + resData);
          that.curDetail.docPicFiles.splice(0, that.curDetail.docPicFiles.length);
          that.confirmSubOrderFn();
        });
        return;
      }

      that.curDetail.customPic = that.curDetail.customPic.split(SPLIT_COMMA).filter(s => s != SPLIT_BLANK).join(SPLIT_COMMA);
      that.curDetail.docPic = that.curDetail.docPic.split(SPLIT_COMMA).filter(s => s != SPLIT_BLANK).join(SPLIT_COMMA);

      let detail = deepCopy(that.curDetail);
      that.showChangeDetailPopup = false;
      if(that.curDetail.flag == 1) {
        that.details.push(detail);
      }

      if(!detail.num || detail.num == SPLIT_BLANK) {
        detail.num = 0;
      }
      if(!detail.metre || detail.metre == SPLIT_BLANK) {
        detail.metre = 0;
      }

      if(detail.id > 0) {   //有ID的是更改
        //直接单个更新
        changeSubOrder(detail, () => {
          that.optSuccessFn(that, "更改成功");
        });
      } else if(that.order.id > 0 && detail.flag == 1) {    //在原有基础下单独增加详情 因为主订单确认只会更改
        addSubOrder(detail, id => {   //成功后设置新增的id和flag=0
          that.optSuccessFn(that, "新增成功");
          detail.id = id;
          detail.flag = 0;
        });
      } else if(detail.id <= 0 && detail.flag == 2) {   //新增后码上更改
        that.details[that.curDetailIndex] = deepCopy(that.curDetail);
        delete that.details[that.curDetailIndex].customPicFiles;
        delete that.details[that.curDetailIndex].docPicFiles;
      }
    },

    /* 预览大图片 */
    showImagePreViewFn(subOrder) {
      let that = this;
      that.preViewPics.splice(0, that.preViewPics.length);
      if(subOrder.viewPics.length > 0) {
        subOrder.viewPics.forEach(picObj => {
          that.preViewPics.push(picObj);
        });
        that.showImagePreView = true;
        return;
      }

      /* 从后端加载 */
      if(subOrder.docPic && subOrder.docPic != SPLIT_COMMA) {
        subOrder.docPic.split(SPLIT_COMMA).forEach(pic => {
          subOrder.viewPics.push({
            name: pic,
            url: SPLIT_BLANK
          });
        });
      }
      if(subOrder.customPic && subOrder.customPic != SPLIT_COMMA) {
        subOrder.customPic.split(SPLIT_COMMA).forEach(pic => {
          subOrder.viewPics.push({
            name: pic,
            url: SPLIT_BLANK
          });
        });
      }
      if(subOrder.viewPics.length > 0) {
        that.showImagePreViewSubFn(subOrder, subOrder.viewPics, 0);
      }
    },
    showImagePreViewSubFn(subOrder, viewPics, index) {
      const that = this;
      let curPicOjb = viewPics[index];
      loadPic(that, curPicOjb.name, picUrl => {
        curPicOjb.url = picUrl;
        that.preViewPics.push(curPicOjb);
        ++index;
        if(viewPics.length > index) {
          that.showImagePreViewSubFn(subOrder, viewPics, index);
        } else {
          if(that.preViewPics.length > 0) {
            that.showImagePreView = true;
          }
        }
      });
    },

    //搜索品名 品名相关
    searchDesignFn(param) {
      let that = this;
      that.designNoData.splice(0, that.designNoData.length);
      filterDesignByNo({
        no: param,
      }, (res) => {
        if (res.length) {
          res.forEach(item => {
            item.name = (item.no + "-" + item.name);
            that.designNoData.push(item);
          });
          that.showDesignPopup = true;
        } else {
          that.$toast.fail("筛选无数据");
        }
      });
    },
    //确认选择品名
    confirmDesignNoFn(design) {
      let that = this;
      that.curDetail.designId = design.id;
      that.curDetail.designNo = design.no;
      that.curDetail.color = design.colorNo;
      that.loadPics(that, design);
      that.showDesignPopup = false;
      that.$forceUpdate();
    },
    //搜索色号
    searchColorFn(param) {
      let that = this;
      that.colorNoData.splice(0, that.colorNoData.length);
      dyeColorFilter({
        keyLike: param,
        pageSize: 50
      }, res => {
        if(res.list.length > 0) {
          res.list.forEach(item => {
            item.vName = (item.no + "#" + item.name);
            that.colorNoData.push(item);
          });
          that.showColorPopup = true;
        } else {
          that.$toast.fail("筛选无数据");
        }
      });
    },
    //确认色号
    confirmColorNoFn(color) {
      let that = this;
      that.curDetail.color = color.vName;
      that.showColorPopup = false;
      that.$forceUpdate();
    },

    //加载图片
    loadPics(that, res) {
      if(res.samplePic && res.samplePic != SPLIT_BLANK) {
        getUploadKey({
          type: "YPSJD"
        }, tokenRes => {
          let samplePicUrl  = exportBaseUrl("res") + "/res/" + res.samplePic + '?accessToken=' + tokenRes.accessToken;
          that.curDetail.samplePicUrl = samplePicUrl;
        });
      }
      if(res.productPic && res.productPic != SPLIT_BLANK) {
        getUploadKey({
          type: "YPSJD"
        }, tokenRes => {
          let productPicUrl  = exportBaseUrl("res") + "/res/" + res.productPic + '?accessToken=' + tokenRes.accessToken;
          that.curDetail.productPicUrl = productPicUrl;
        });
      }
    },

    //查询客户信息
    searchCustomerFn(param) {
      let that = this;
      that.customerData.splice(0, that.customerData.length);
      getCustomerInfoList({
        name: param,
      }, (res) => {
        if (res.list.length) {
          res.list.forEach((item) => {
            item.name = item.company + "_" + item.name;
            that.customerData.push(item);
            that.showCustomerPopup = true;
          });
        } else {
          that.$toast.fail("没有客户数据");
        }
      });
    },
    //确认选择顾客
    confirmCustomerFn(customer) {
      let that = this;
      that.order.channel = customer.channel;
      that.order.customerId = customer.id;
      that.order.customerName = customer.name;
      that.showCustomerPopup = false;
    },

    // 强制更新视图
    viewUpdateFn() {
      this.$forceUpdate();
    },

    //增加颜色
    addDyeColorFn() {
      let that = this;
      addDyeColor(that.colorParam, () => {
        that.curDetail.color = that.colorParam.no.toUpperCase() + "#" + that.colorParam.name
        that.showAddColorPopup = false;
      });
    },

    //确认更改
    confirmChangeFn() {
      let that = this;
      if(that.order.id > 0) {   //只更改主订单内容 子订单单独操作增删改查
        changeOrder(that.order, () => {
          that.$toast.success({
            message: "修改成功",
            overlay: true,
            onClose: function() {
              comeBack();
            }
          });
        });
      } else {
        that.order.details = that.details;
        addOrder(that.order, () => {
          that.$toast.success({
            message: "下单成功",
            overlay: true,
            onClose: function() {
              comeBack();
            }
          });
        });
      }
    },

    //查看库存
    showStockPopupFn(opt, detail, index) {
      let that = this;
      that.curDetailIndex  = index;
      that.viewStockFlag = opt;
      if(detail.designNo == SPLIT_BLANK || detail.color == SPLIT_BLANK) {
        that.$toast.fail("品名和颜色必须");
        return;
      }
      if(opt == 1) {
        if(!detail.designId || detail.designId == 0 || detail.designId == SPLIT_BLANK) {
          that.$toast.fail("当前详情无设计品号,请搜索选择或者先派任务给开发设计部门");
          return;
        }
        that.showYarnStockPopup = true;
        that.loadYarnStoreFn(that, detail);
      } else if(opt == 2) {
        that.showClothStockPopup = true;
        that.loadGreyClothStoreFn(that, detail);
      } else if(opt === 3) {
        that.showClothStockPopup = true;
        that.loadProductClothStoreFn(that, detail);
      }
    },

    //加载纱线库存
    loadYarnStoreFn(that, detail) {
      that.detail4Stocks.splice(0, that.detail4Stocks.length);
      //获取纱线
      loadSampleYarn({
        designFormId: detail.designId,
        type: 2
      }, data => {
        data.forEach(row => {
          row.expectUsage = getFloat(detail.metre / 100 * row.yarnUsage, 1);
          loadYarnStandardBatch({
            standardId: row.yarnId
          }, batchs => {
            batchs.forEach(batch => {
              /*if(batch.stock <= 0 && batch.expectStock <= 0) {    //要求显示 有预计需求
                return;
              }*/
              batch.standardNo = batch.no;
              batch.yarnNo = row.yarnNo;
              batch.yarnStandard = row.yarnStandard;
              batch.yarnStrandNum = row.yarnStrandNum;
              batch.expectUsage = row.expectUsage;

              if((batch.stock + batch.expectStock) < batch.expectUsage) {
                batch.stockStyle = "color: #9a2a01"
              } else if(batch.stock >= batch.expectUsage) {
                batch.stockStyle = "color: #109304"
              } else if((batch.stock + batch.expectStock) >= batch.expectUsage && batch.stock < batch.expectUsage) {
                batch.stockStyle = "color: #d39826";
              } else {
                batch.stockStyle = "color: #9a2a01"
              }

              that.detail4Stocks.push(batch);
            });
          });
        });
      });
    },

    //加载坯布库存
    loadGreyClothStoreFn(that, detail) {
      that.detail4Stocks.splice(0, that.detail4Stocks.length);
      loadGreyClothStore({
        designNo: detail.designNo,
        color: detail.color
      }, data => {
        data.forEach(row => {
          if((row.totalNum + row.expectNum) > 0) {    //匹数大于0的
            that.detail4Stocks.push(row);
            that.renderStockStyleFn(that, row, detail);
          }
        });
      });

      //不含999的都查下白坯
      if(detail.color.indexOf("999") == -1) {
        loadGreyClothStore({
          designNo: detail.designNo,
          color: "999"
        }, data => {
          data.forEach(row => {
            if((row.totalNum + row.expectNum) > 0) {    //匹数大于0的
              that.detail4Stocks.push(row);
              that.renderStockStyleFn(that, row, detail);
            }
          });
        });
      }
    },

    //加载成品库存
    loadProductClothStoreFn(that, detail) {
      that.detail4Stocks.splice(0, that.detail4Stocks.length);
      let colors = detail.color.split("#");
      loadProductClothStore({
        designNo: detail.designNo,
        color: colors.length > 1 ? colors[1] : colors[0]
      }, data => {
        data.forEach((row) => {
          row.expectNum = row.exceptNum;    //修正单词拼写错误
          // if((row.totalNum + row.expectNum) > 0) {    //匹数大于0的
            that.detail4Stocks.push(row);
            that.renderStockStyleFn(that, row, detail);
          // }
        });
      });
    },

    //渲染库存颜色
    renderStockStyleFn(that, row, detail) {
      if((row.totalNum + row.expectNum) < detail.num) {
        row.stockStyle = "color: #9a2a01"
      } else if(row.totalNum >= detail.num) {
        row.stockStyle = "color: #109304"
      } else if((row.totalNum + row.expectNum) >= detail.num && row.totalNum < detail.num) {
        row.stockStyle = "color: #d39826";
      } else {
        row.stockStyle = "color: #9a2a01"
      }
    },

    //展示岗位弹窗
    /*showPostPopupFn(task) {
      let that = this;
      that.showPostPopup = true;
      that.curTask = task;    //当前任务 从子订单直接过来=null
      that.postData.splice(0, that.postData.length);
      that.postCheckedData.splice(0, that.postCheckedData.length);    //清空选中
      loadPost({}, data => {
        data.forEach(post => {
          post.role = ("," + post.depId + "_" + post.id + ",");
        });

        let roles = "," + getInfo().roles + ",";
        let curPost = data.find(post => roles.indexOf(post.role) >= 0);
        if(!curPost) {
          that.$toast.fail("当前用户所在部门不在业务派单内");
          return;
        }

        if(curPost.appointTo == "0") {
          data.filter(post => post.show == 1).forEach(post => {
            post.disabled = false;
            that.postData.push(post);
          });
        } else {
          let appointToPosts = curPost.appointTo.split(",");
          data.filter(post => post.show == 1).forEach(post => {
            if(appointToPosts.findIndex(appointTo => appointTo == post.id) >= 0) {
              post.disabled = false;
            } else {
              post.disabled = true;
            }
            that.postData.push(post);
          });
        }

        //当前的部门的去掉
        that.postData.forEach(post => {
          if(roles.indexOf(post.role) != -1) {
            post.disabled = true;
          }

          post.role = (post.depId + "_" + post.id);   //不要首末逗号
        });
      });
    },*/

    //派任务
    /*appointTaskFn() {
      let that = this;
      if(that.postCheckedData.length == 0) {
        that.$toast.fail("请选择部门");
        return;
      }
      if(!that.order.id) {
        that.$toast.fail("请先确认订单再派发任务");
        return;
      }

      let curTaskId = 0;  //开始下单=0
      if(that.curTask) {
        curTaskId = that.curTask.id;
      }
      let orderTasks = [];
      that.appointTaskSubFn(that, orderTasks, that.details[that.curDetailIndex], curTaskId);   //当前子任务
      appointTask(orderTasks, () => {
        that.optSuccessFn(that, "任务派发成功");
      });
    },
    appointTaskSubFn(that, orderTasks, detail, curTaskId) {
      that.postCheckedData.forEach(postChecked => {
        let data = {
          originalId: curTaskId,
          depPost: postChecked.role,
          orderId: that.order.id,
          subOrderId: detail.id,
          appointRemark: that.specialRemark,
          depPostName: postChecked.name,
          executiveName: postChecked.firstUser,
          executiveMobile: postChecked.executiveMobile
        }
        orderTasks.push(data);
      });
    },*/

    //驳回任务
    /*rejectTaskFn(task) {
      let that = this;
      rejectTask({
        taskId: task.id,
        appointRemark: that.executiveRemark,
      }, () => {
        that.optSuccessFn(that, "任务驳回成功");
      });
    },*/

    //面板展开接单
    /*subOrderCollapseChangeFn(activeNames) {
      let that = this;
      let detail = that.details[activeNames];
      if(detail && detail.tags && detail.tags.length > 0 && detail.tags.some(t => t.value == 3)) {   //待接单
        acceptTask({
          orderId: that.order.id,
          subOrderId: detail.id
        }, () => {
          that.optSuccessFn(that, "接单成功");
        });
      }
    },*/

    //完成任务
    /*finishTaskFn(task) {
      let that = this;
      finishTask({
        taskId: task.id,
        executiveRemark: that.executiveRemark
      }, () => {
        that.optSuccessFn(that, "完成任务");
      });
    },*/

    //撤销任务
    /*cancelTaskFn(task) {
      let that = this;
      cancelTask({
        taskId: task.id
      }, () => {
        that.optSuccessFn(that, "撤销任务成功", true);
        that.orderTaskData.splice(that.orderTaskData.findIndex(t => t.id == task.id), 1);
      });
    },*/

    //操作成功后
    optSuccessFn(that, msg, keepFlag) {
      that.$toast.success(msg);
      if(!keepFlag) {
        that.showOrderTaskPopup = false;
        that.showPostPopup = false;
        that.showChangeDetailPopup = false;
      }
      // that.curTask = null;    //派单完成或者任务完成或者驳回 这个必须重置
      that.loadClothSubOrderFn(that, that.order.id);
    },

    //任务查看
    /*viewTaskFn(detail, index) {
      let that = this;
      that.curDetailIndex = index;    //当前详情索引
      that.orderTaskData.splice(0, that.orderTaskData.length);
      loadOrderTaskBySubOrder({
        orderId: that.order.id,
        subOrderId: detail.id,
      }, res => {
        if(!res.code && res.code != 0 && res) {
          res.forEach(task => {
            that.orderTaskData.push(task);
            task.mine = (task.executiveId == getInfo().userId);
            task.statusName = orderTaskStatusEnum(task.status);   //状态翻译
            that.showOrderTaskPopup = true;
          });
        } else {
          that.showPostPopupFn(null);
        }
      });
    },*/

    //待处理背景
    /*taskBackgroundColorFn(task) {
      let roles = "," + getInfo().roles + ",";
      if((roles.indexOf(task.depPost) > 0 && task.depPost != SPLIT_BLANK && task.status == 1) || getInfo().userId == task.executiveId) {
        if(task.status == 3) {
          return "background: #b7e791";
        } else if(task.status == 4) {   //处理人驳回
          return "background: #fda7af";
        } else {
          return "background: #ece17d";
        }
      }

      //发单人被驳回的
      if(task.status == 4 && (getInfo().userId == task.appointorId || getInfo().userId == task.executiveId)) {
        return "background: #fda7af";
      }

      return SPLIT_BLANK;
    },*/

    //焦点获取清空输入框准备计算
    toClearFieldFn(field) {
      let that = this;
      if("metre" == field && that.curDetail.num > 0 && that.curDetail.length > 0) {
        that.curDetail.num = SPLIT_BLANK;
      }
      if("num" == field && that.curDetail.metre > 0 && that.curDetail.length > 0) {
        that.curDetail.metre = SPLIT_BLANK;
      }
      if("length" == field && that.curDetail.metre > 0 && that.curDetail.num > 0) {
        that.curDetail.metre = SPLIT_BLANK;
      }
    },

    //计算第三个
    calFieldFn(field) {
      let that = this;
      that.toClearFieldFn(field);
      clearTimeout(that.calTimer);
      that.calTimer = setTimeout(() => {
        if("num" == field) {
          if(that.curDetail.length > 0 && that.curDetail.metre == SPLIT_BLANK) {
            that.curDetail.metre = that.curDetail.num * that.curDetail.length;
          } else if(that.curDetail.metre > 0 && that.curDetail.length == SPLIT_BLANK) {
            that.curDetail.length = Math.floor(that.curDetail.metre / that.curDetail.num);
          }
        }
        if("length" == field) {
          if(that.curDetail.num > 0 && that.curDetail.metre == SPLIT_BLANK) {
            that.curDetail.metre = that.curDetail.num * that.curDetail.length;
          } else if(that.curDetail.metre > 0 && that.curDetail.num == SPLIT_BLANK) {
            that.curDetail.num = Math.ceil(that.curDetail.metre / that.curDetail.length);
          }
        }
        if("metre" == field) {
          if(that.curDetail.length > 0 && that.curDetail.num == SPLIT_BLANK) {
            that.curDetail.num = Math.ceil(that.curDetail.metre / that.curDetail.length);
          } else if(that.curDetail.num > 0 && that.curDetail.length == SPLIT_BLANK) {
            that.curDetail.length = Math.floor(that.curDetail.metre / that.curDetail.num);
          }
        }
      }, 1500);
    },

    //选择品号
    selectDesignNoFn(stock) {
      let that = this;
      //只有坯染能点
      let roles = "," + getInfo().roles + ",";
      if(roles.indexOf(",3496_3497,") >= 0) {     //这里暂时写死 坯染车间才能操作 fixme
        let detail = that.details[that.curDetailIndex];
        that.$dialog.confirm({
          title: "请确认",
          message: "确定选择该坯布?"
        }).then(() => {
          //绑定designId
          changeSubOrderDesign({
            id: detail.id,
            designId: stock.designId,
            designNo: stock.designNo
          }, res => {
            this.loadClothSubOrderFn(that, detail.orderId);
          });

          //处理备注信息
          if(that.selectStock && that.selectStock.designNo && that.executiveRemark != SPLIT_BLANK) {
            that.executiveRemark = that.executiveRemark.substring(that.selectStock.designNo.length, that.executiveRemark.length);
          }
          that.executiveRemark = (stock.designNo ? stock.designNo : SPLIT_BLANK)  + " " + that.executiveRemark;

          if(that.selectStock && that.selectStock.designNo && that.specialRemark != SPLIT_BLANK) {
            that.specialRemark = that.specialRemark.substring(that.selectStock.designNo.length, that.specialRemark.length);
          }
          that.specialRemark = (stock.designNo ? stock.designNo : SPLIT_BLANK)  + " " + that.specialRemark;
          that.selectStock = stock;

          //直接弹任务列表
          // that.viewTaskFn(detail, that.curDetailIndex);
        }).catch(msg => {
          console.log("--->msg", msg);
        });
      }
    },

    /* 查看环节 */
    viewStepFn(subOrder) {
      const that = this;
      if(!subOrder.steps || subOrder.steps.length == 0) {
        that.$toast.fail("没有环节数据")
        return;
      }
      that.step.data.splice(0, that.step.data.length);
      subOrder.steps.filter(s => s.optId == getInfo().userId).forEach(s => {
        s.optFlag = true;
        that.handleOptRemarkFn(s);
        that.step.data.push(s);
      });
      subOrder.steps.filter(s => s.optId != getInfo().userId).forEach(s => {
        s.optFlag = false;
        that.handleOptRemarkFn(s);
        that.step.data.push(s);
      });
      that.step.show = true;
    },
    handleOptRemarkFn(s) {
      s.opts = [];
      if(s.optRemark && s.optRemark.indexOf("[") == 0) {
        JSON.parse(s.optRemark).forEach(optR => {
          optR.c = false;
          s.opts.push(optR);
        });
      }
      s.opts.push({
        c: true,
        text: SPLIT_BLANK,    //与后端一直
        t: dayjs().format("YYYY-MM-DD HH:mm:ss")    //与后端一直
      });

    },

    /* 处理环节 */
    handleStepFn(step, opt) {
      const that = this;

      //处理备注
      let curRemark = step.opts.find(optR => optR.c);
      if(!curRemark) {
        that.$toast.fail("程序出错");
        return;
      }
      if(step.status == 1 && opt == 2) {
        curRemark.text = "已接单:" + curRemark.text;
      } else if(step.status == 2 && opt == 3) {
        curRemark.text = "已完成:" + curRemark.text;
      }
      if(curRemark.text.length < 4) {
        that.$toast.fail("备注必须大于3个字");
        return;
      }
      let optRemark = deepCopy(step.opts);
      optRemark.forEach(optR => {
        delete optR.c;
      })
      step.optRemark = JSON.stringify(optRemark);

      //发起请求
      let curStatus = step.status;
      step.status = opt;
      handleStep(step, resData => {
        if(resData.code || resData.code == 0) {
          step.status = curStatus;
          that.$toast.fail(resData.msg);
          return;
        }
        that.$toast.success({
          message: "操作成功",
          onClose: () => {
            if(step.status == 2) {
              step.lastOptAt = dayjs().format("YYYY-MM-DD HH:mm:ss");
            } else if(step.status == 3) {
              step.finishAt = dayjs().format("YYYY-MM-DD HH:mm:ss");
            }
            that.step.show = false;
          }
        });
        that.$forceUpdate();
      });
    },

    /* 上传图片 */
    uploadPicFn(files, callback) {
      const that = this;
      if(files.length <= 0) {
        that.$toast("没有待上传的图片");
        return;
      }
      uploadPic(that, "YWXD", files, resData => {
        if(callback) {
          callback(resData);
        }
      });
    },

    /* 显示订单详情 */
    showSubOrderFn(index) {
      const that = this;
      let subOrder = that.details[index];
      that.loadFirstPicFn(subOrder);
    },
    /* 加载首图 */
    loadFirstPicFn(subOrder) {
      const that = this;
      let firstPic = SPLIT_BLANK;
      if(subOrder.firstPic == SPLIT_BLANK) {
        if(subOrder.docPic && subOrder.docPic != SPLIT_COMMA) {
          firstPic = subOrder.docPic.split(SPLIT_COMMA)[0];
        } else if(subOrder.customPic && subOrder.customPic != SPLIT_COMMA) {
          firstPic = subOrder.customPic.split(SPLIT_COMMA)[0];
        }
        if(firstPic != SPLIT_BLANK) {
          loadPicThumb(that, firstPic, resData => {
            subOrder.firstPic = resData;
          });
        }
      }
    },

    /* 删除图片 */
    delPicFn(pics, picObj, pIndex) {
      const that = this;
      pics.splice(pIndex, 1);
      let subOrder = that.details[that.curDetailIndex];
      if(subOrder.customPic.indexOf(picObj.name) != -1) {
        subOrder.customPic = subOrder.customPic.replace(picObj.name, SPLIT_BLANK).split(SPLIT_COMMA).filter(p => p != SPLIT_BLANK).join(SPLIT_COMMA);
        that.curDetail.customPic = that.curDetail.customPic.replace(picObj.name, SPLIT_BLANK).split(SPLIT_COMMA).filter(p => p != SPLIT_BLANK).join(SPLIT_COMMA);
      }
      if(subOrder.docPic.indexOf(picObj.name) != -1) {
        subOrder.docPic = subOrder.docPic.replace(picObj.name, SPLIT_BLANK).split(SPLIT_COMMA).filter(p => p != SPLIT_BLANK).join(SPLIT_COMMA);
        that.curDetail.docPic = that.curDetail.docPic.replace(picObj.name, SPLIT_BLANK).split(SPLIT_COMMA).filter(p => p != SPLIT_BLANK).join(SPLIT_COMMA);
      }
    },

    /* 单个预览 */
    showImagePreViewSingleFn(picObj) {
      const that = this;
      let subOrder = that.details[that.curDetailIndex];
      if(subOrder.viewPics.length > 0) {
        let singleView = subOrder.viewPics.find(viewPic => viewPic.name == picObj.name);
        if(singleView) {
          that.preViewPics.splice(0, that.preViewPics.length);
          that.preViewPics.push(singleView);
          that.showImagePreView = true;
          return;
        }
      }
      loadPic(that, picObj.name, resData => {
        let tmpObj = {
          name: picObj.name,
          url: resData
        };
        that.preViewPics.splice(0, that.preViewPics.length);
        that.preViewPics.push(tmpObj);
        subOrder.viewPics.push(tmpObj);
        that.showImagePreView = true;
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.cloth-order-change {
  ::v-deep .van-radio-group {
    .van-radio__icon--disabled .van-icon {
      background-color: #1989fa;
    }
    .van-radio__label--disabled {
      color: #000000;
    }
  }
}
</style>
<style lang="scss">
.cloth-order-change {
  .van-search {
    width: 100%;
    z-index: 1;
    padding: 0px;
    .van-search__content {
      padding: 0px;
    }
  }
  .van-swipe-cell__right {
    display: flex;
    flex-flow: column;
  }
  .van-card__footer {
    .van-button {
      height: 25px;
    }
  }
  //更改弹窗
  .change-detail-popup {
    width: 90%;
    padding: 5px 0px;
    .van-button {
      width: 150px;
      margin-left: 15px;
      height: 35px;
    }
  }

  //部门选择样式
  .van-checkbox-group {
    display: flex;
    flex-flow: column;
    align-items: center;
    padding-top: 10px;
    .van-checkbox {
      padding:10px;
      width: 220px;
      .van-checkbox__icon {
        font-size: 18px;
      }
      .van-checkbox__label {
        font-size: 20px;
      }
    }
  }
  .van-field-label-remark {
    font-size: 16px;
    color: #e6a23c;
  }

  //任务列表样式
  .order-task-card {
    width: 96%;
    box-shadow: 5px 5px 5px #888888;
    margin-top: 10px;
    margin-left:10px;
    .van-row {
      margin-top:5px;
      .task-label {
        text-align: right;
        line-height: 20px;
      }
      .task-body {
        line-height: 20px;
        margin-left: 5px;
      }
    }
    .van-row-appoint {
      color: #2083fd;
    }
    .van-row-accept {
      color: #b4570f;
    }
  }
}

</style>